import {useRef} from 'react';
import {useDrop, DropTargetMonitor, useDrag, DragSourceMonitor} from 'react-dnd';

interface DraggableBodyRowProps extends React.HTMLAttributes<HTMLTableRowElement> {
    index: number;
    record: any;
    moveRow: (dragBefore: any, dragAffter: any) => void;
};

const DraggableBodyRow = ({record, moveRow, className, style, ...restProps}: DraggableBodyRowProps) => {
    const ref = useRef<HTMLTableRowElement>(null);
    const [{isOver, dropClassName}, drop] = useDrop({
        accept: 'DraggableBodyRow',
        collect: (monitor: DropTargetMonitor) => ({
            isOver: monitor.isOver(),
            dropClassName: ' drop-over-upward',
        }),
        drop: (item: any) => {
            moveRow(item, record);
        },
    });

    const [, drag] = useDrag({
        type: 'DraggableBodyRow',
        item: record,
        collect: (monitor: DragSourceMonitor) => ({
            isDragging: monitor.isDragging(),
        }),
    });
    drop(drag(ref));

    return (
        <tr
            ref={ref}
            className={`${className}${isOver ? dropClassName : ''}`}
            style={{cursor: 'move', ...style}}
            {...restProps}
        />
    );
};

export default DraggableBodyRow;
